﻿Imports System.Windows.Forms
Imports System.IO
Imports System.Text

Public Class TextFileIO

    ''' <summary>
    ''' 打开text文件
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function importdata() As String
        ''打开文件对话框
        Dim openDlg = New OpenFileDialog()
        ''文件过滤条件
        openDlg.Filter = "工程数据文件|*.txt"
        ''初始文件夹为系统桌面
        openDlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        If openDlg.ShowDialog() = DialogResult.OK Then
            ''返回选择的文件名
            Return openDlg.FileName
        Else
            Return Nothing
        End If
    End Function

    ''' <summary>
    ''' 读取并处理文件
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function readdata(filename As String)
        Dim sr As StreamReader = New StreamReader(filename, System.Text.Encoding.UTF8)
        ''根据情况定数组linedata的大小（示例为3）
        Dim linedata(3) As String
        Do While sr.Peek() > 0
            linedata = sr.ReadLine().Split(",") '英文逗号分割每行数据
            If linedata(0) = "" Then
                Continue Do
            End If
            ''linedata是每一行按照分割符分割后得到的数组
            ''处理每一行的数据
            ''.......
        Loop
        sr.Close()
        sr = Nothing
    End Function

    ''' <summary>
    ''' 输出数据到文件
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function outputdata()
        Dim sf = New SaveFileDialog()
        sf.Filter = "Text File|*.txt"
        sf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        If sf.ShowDialog() = DialogResult.OK Then
            Dim sw As StreamWriter = New StreamWriter(sf.FileName, True, ASCIIEncoding.UTF8)  'true是指以追加的方式打开指定文件  
            ''总行数linecount
            Dim linecount As Integer
            linecount = 10
            ''循环写入文件
            For i As Integer = 0 To linecount
                ''tempstring是每行的数据
                Dim tempstring As String
                tempstring = "123"  ''示例数据123
                ''写入当前行
                sw.WriteLine(tempstring)
                sw.Flush()
            Next
            sw.Close()
            sw = Nothing
        Else
            Return Nothing
        End If

    End Function

End Class
